package com.moon.controller;

import com.auth0.jwt.internal.com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moon.dao.TAuctionMapper;
import com.moon.entity.TAuction;
import com.moon.es.ESDataWriter;
import com.moon.es.ESTAuctionRepository;
import com.moon.vo.EsTAuction;
import com.moon.vo.TAuctionVo;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/tauctionUnlogin")
@Controller
public class TAuctionUnloginController {
    @Autowired
    private TAuctionMapper tAuctionMapper;

    @Autowired
    ESTAuctionRepository estAuctionRepository;

    @Autowired
    @Qualifier("esTAuction")
    ESDataWriter esDataWriter;

    @RequestMapping("/selectAllTAuction")
    @ResponseBody
    public PageInfo<TAuctionVo> selectAllTAuction(@RequestParam(defaultValue = "1") Integer currentPage,
                                              @RequestParam(defaultValue = "3") Integer pageSize,
                                              @RequestParam(defaultValue = "") String keyword){
        System.out.println("---TAunlogin_slAllTA---");
        PageHelper.startPage(currentPage,pageSize);
        List<TAuctionVo> tAuctions = tAuctionMapper.selectAllTAuctionVo();
        PageInfo<TAuctionVo> pageInfo = new PageInfo<>(tAuctions);
//        System.out.println("███pageInfo: "+pageInfo);
        return pageInfo;
    }

    @RequestMapping("/selectTAuction")
    @ResponseBody
    public TAuctionVo selectTAuction(Long auctionId){
        System.out.println("---TAunlogin_slTA---");
        return tAuctionMapper.selectById(auctionId);
    }


    @RequestMapping("/searchByES")
    @ResponseBody
    public Page<EsTAuction> searchByES(@RequestParam(defaultValue = "1") Integer currentPage,
                                       @RequestParam(defaultValue = "3") Integer pageSize,
                                       @RequestParam(defaultValue = "") String keyword,
                                       @RequestParam(defaultValue = "-1") Integer status,
                                       @RequestParam(defaultValue = "") BigDecimal startPrice,
                                       @RequestParam(defaultValue = "") BigDecimal endPrice,
                                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                       @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                       @RequestParam(defaultValue = "") Date startTime,
                                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                       @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                       @RequestParam(defaultValue = "") Date endTime,
                                       @RequestParam(defaultValue = "0") Integer sortBySth) {
        System.out.println("---TAunlogin_searchByES---");
//        System.out.println("███currentPage: "+currentPage+" pageSize: "+pageSize+" keyword: "+keyword+" status: "+status);
//        System.out.println("███startPrice: "+startPrice+" endPrice: "+endPrice+" sortBySth: "+sortBySth);
        System.out.println("startTime: "+startTime+" endTime: "+endTime);
        //判断es是否有数据,如果没有数据就写入
        //fixme 每次都重新删除再写入
//        if (!estAuctionRepository.findAll().iterator().hasNext())
        estAuctionRepository.deleteAll();
        esDataWriter.dataWrite();
        //es查询

        //构建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        //查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //字段模糊
        if (null != keyword && !"".equals(keyword)){
//            System.out.println("███keyword:"+keyword);
            boolQueryBuilder.must(QueryBuilders.multiMatchQuery(keyword,"productName","productDetail"));
        }
        //字段精确
        if (status != -1 && !"".equals(status) && null != status){
//            System.out.println("███status:"+status);
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("status", status);
            boolQueryBuilder.must(termQueryBuilder);
        }
        //价格范围查询
        if (null != startPrice && !"".equals(startPrice) && (null == endPrice || "".equals(endPrice))){
//            System.out.println("███startPrice:"+startPrice);
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("basePrice").gte(startPrice);
            boolQueryBuilder.must(rangeQueryBuilder);
        }
        if (null != endPrice && !"".equals(endPrice) && (null == startPrice || "".equals(startPrice))){
//            System.out.println("███endPrice:"+endPrice);
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("basePrice").lte(endPrice);
            boolQueryBuilder.must(rangeQueryBuilder);
        }
        if (null != startPrice && !"".equals(startPrice) && null != endPrice && !"".equals(endPrice)){
//            System.out.println("███startPrice:"+startPrice+" endPrice:"+endPrice);
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("basePrice").from(startPrice).to(endPrice);
            boolQueryBuilder.must(rangeQueryBuilder);
        }
        //时间范围查询
        if (null != startTime && !"".equals(startTime) && (null == endTime || "".equals(endTime))){
//            System.out.println("███startPrice:"+startPrice);
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("startTime").gte(startTime);
            boolQueryBuilder.must(rangeQueryBuilder);
        }
        if (null != endTime && !"".equals(endTime) && (null == startTime || "".equals(startTime))){
//            System.out.println("███endPrice:"+endPrice);
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("startTime").lte(endTime);
            boolQueryBuilder.must(rangeQueryBuilder);
        }
        if (null != startTime && !"".equals(startTime) && null != endTime && !"".equals(endTime)){
//            System.out.println("███startPrice:"+startPrice+" endPrice:"+endPrice);
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("startTime").from(startTime).to(endTime);
            boolQueryBuilder.must(rangeQueryBuilder);
        }
        //排序
//        System.out.println("███sort");
        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("");
        if (0 != sortBySth && null != sortBySth && !"".equals(sortBySth)){
//            System.out.println("███SortBySth:"+sortBySth);
            if(sortBySth == 1){
                //最新发布
                fieldSortBuilder = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
            }else if(sortBySth == 2){
                //开拍时间降序
                fieldSortBuilder = SortBuilders.fieldSort("startTime").order(SortOrder.DESC);
            }else if(sortBySth == 3){
                //价格升序
                fieldSortBuilder = SortBuilders.fieldSort("basePrice").order(SortOrder.ASC);
            }else if(sortBySth == 4){
                //价格降序
                fieldSortBuilder = SortBuilders.fieldSort("basePrice").order(SortOrder.DESC);
            }else if(sortBySth == 5){
                //热度排序(参与人数,不是浏览人数)
                fieldSortBuilder = SortBuilders.fieldSort("joinCount").order(SortOrder.DESC);
            }
        } else {
            fieldSortBuilder = SortBuilders.fieldSort("id").order(SortOrder.DESC);
        }

        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        nativeSearchQueryBuilder.withSort(fieldSortBuilder);

//        System.out.println("███page");
        //分页条件
        //注意: es中的分页是从第0页开始的
        nativeSearchQueryBuilder.withPageable(PageRequest.of(currentPage - 1, pageSize));


        Page<EsTAuction> search = estAuctionRepository.search(nativeSearchQueryBuilder.build());
        return search;
    }

    @RequestMapping("/getNewTAuctions")
    @ResponseBody
    public Page<EsTAuction> getNewTAuctions(@RequestParam(defaultValue = "1") Integer currentPage,
                                            @RequestParam(defaultValue = "3") Integer pageSize) {
//        System.out.println("startTime: "+startTime);
//        System.out.println("endTime: "+endTime);
        Date today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
//        System.out.println("███today: "+today);
        Date tommorrow = new Date(today.getTime() + 1000*60*60*24 -1);
//        System.out.println("███tommorrow"+tommorrow);
        searchByES(currentPage,pageSize,null,null,null,null,today,tommorrow,null);
        return null;
    }

}
